package com.zxzw.scanningin.http

import android.text.TextUtils
import android.util.Log
import okhttp3.*
import okio.Buffer
import okio.BufferedSource
import java.io.IOException
import java.nio.charset.StandardCharsets

/**
 * 网络请求的日志拦截器
 * 打印请求信息 如请求链接 请求参数 请求时间 请求结果等
 */
class LogcatInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val startTime = System.currentTimeMillis() //请求发起时间
        val response = chain.proceed(request)
        val finishTime = System.currentTimeMillis() //请求结束时间
        print(finishTime - startTime, request, response)
        return response
    }

    /**
     * 打印日志信息
     *
     * @param time    请求耗时
     * @param request 请求
     */
    @Throws(IOException::class)
    private fun print(time: Long, request: Request, response: Response) {
        Log.e(TAG, "*********************发起请求开始*********************************")
        Log.e(TAG, "请求链接：" + request.url())
        Log.e(TAG, "请求方式：" + request.method())
        Log.e(TAG, "请求耗时：" + time + "ms")
        if (!TextUtils.isEmpty(request.headers().toString())) Log.e(
            TAG,
            "请求头：" + request.headers().toString()
        )
        val strRequestBody = StringBuilder()
        val requestBody: RequestBody? = request.body()
        //formBody的请求参数
        if (requestBody is FormBody) {
            val body: FormBody = requestBody
            strRequestBody.append("{")
            for (i in 0 until body.size()) {
                if (i > 0) {
                    strRequestBody.append(",")
                }
                strRequestBody.append(body.encodedName(i)).append("=").append(body.encodedValue(i))
            }
            strRequestBody.append("}")
        } else if (requestBody != null) {
            strRequestBody.append(requestBody.toString())
        }
        Log.e(TAG, "请求参数：$strRequestBody")
        Log.e(TAG, "*********************发起请求结束*********************************")
        val body: ResponseBody? = response.body()
        Log.e(TAG, "*********************接收结果开始*********************************")
        Log.e(TAG, "请求的url：" + request.url())
        if (body != null) {
            val source: BufferedSource = body.source()
            source.request(Long.MAX_VALUE)
            val buffer: Buffer = source.buffer
            Log.e(TAG, "請求結果：" + buffer.clone().readString(StandardCharsets.UTF_8))
        } else {
            Log.e(TAG, "請求結果：null")
        }
        Log.e(TAG, "*********************接收结果结束*********************************")
    }

    companion object {
        private const val TAG = "<<<<HTTP REQUEST"
    }
}